package com.chart.web.controller.chart;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.chart.chart.domian.*;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.service.IChartConfigsUserService;
import com.chart.chart.service.IChartFilesService;
import com.chart.chart.service.IChartViewsUserService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.utils.ChartDataUtils;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.bean.BeanUtils;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.IUserCoinLogsService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.chart.common.constant.HttpStatus.CUSTOM_ERROR;
import static com.chart.common.constant.HttpStatus.CUSTOM_EXCEPTION_CODE;
import static com.chart.web.controller.chart.ChartOperationsController.convertDataList;

/**
 * 图表大屏
 *
 * @author chart
 */
@RestController
@RequestMapping("/file/chart")
public class ChartFilesController extends BaseController {

    @Autowired
    private IChartFilesService chartFilesService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IUserCoinLogsService userCoinLogsService;

    @Autowired
    private IChartConfigsUserService chartConfigsUserService;

    @Autowired
    private IChartViewsUserService chartViewsUserService;


    @ApiOperation("文件夹：列表")
    @GetMapping("/user/treeList")
    @Transactional
    public AjaxResult treeLsit(Long fileId) {
        //根据用户信息获取文件夹信息
        Long userId = SecurityUtils.getUserId();
        List<ChartFiles> list = chartFilesService.list(new LambdaQueryWrapper<ChartFiles>().eq(ChartFiles::getUserId, userId));

        for (int i = 0; i < list.size(); i++) {
            List<Long> ids = new ArrayList<>();
            ChartFiles chartFiles = list.get(i);
            ids.add(chartFiles.getFileId());
            //获取文件夹下大屏或者图表信息
            List<ChartConfigsAndViewsVo> configsAndViewsVoList = chartConfigsUserService.getChartsAndViewsBathByFileIds(ids);
            chartFiles.setChartConfigsAndViewsVos(configsAndViewsVoList);
        }


        //将数据转成树结构
        Map<Long, ChartFiles> map = list.stream().collect(Collectors.toMap(ChartFiles::getFileId, ChartFiles -> ChartFiles));
        ArrayList<ChartFiles> chartFiles = new ArrayList<>();
        map.forEach((key, value) -> {
            Optional.ofNullable(value.getParentId())
                    .map(map::get)
                    .ifPresent(pFile -> {
                        List<ChartFiles> children = pFile.getChildren();
                        if (children == null) {
                            pFile.setChildren(Stream.of(value).collect(Collectors.toList()));
                        } else {
                            children.add(value);
                        }
                    });
            if (!ObjectUtils.isEmpty(fileId)) {
                if (!ObjectUtils.isEmpty(value.getParentId())) {
                    if (value.getParentId().equals(fileId)) {
                        chartFiles.add(value);
                    }
                }
            } else {
                if (value.getParentId() == null) {
                    chartFiles.add(value);
                }
            }
        });
        return AjaxResult.success(chartFiles);
    }


/*    @ApiOperation("文件夹：新增")
    @PostMapping("/user/add")
    @Transactional
    public AjaxResult add(@RequestBody ChartFiles chartFiles) {
        if (ObjectUtils.isEmpty(chartFiles.getFileName())) {
            return AjaxResult.error("请填写文件夹名称");
        }
//        chartFiles.setParentId(chartFiles.getFileId());
//        chartFiles.setFileId(null);

        ChartFiles one;
        if (chartFiles.getParentId() == null) {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .isNull(ChartFiles::getParentId)
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        } else {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .eq(ChartFiles::getParentId, chartFiles.getParentId())
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        }
        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("文件夹名称重复");
        }
        chartFiles.setUserId(SecurityUtils.getUserId());
        boolean result = chartFilesService.saveOrUpdate(chartFiles);
        if (result) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }*/


    @ApiOperation("文件夹：新增")
    @PostMapping("/user/add")
    @Transactional
    public AjaxResult add(@RequestBody ChartFiles chartFiles) {
        if (ObjectUtils.isEmpty(chartFiles.getFileName())) {
            return AjaxResult.error("请填写文件夹名称");
        }

        // 检查是否存在重复文件夹名称
        ChartFiles one;
        if (chartFiles.getParentId() == null) {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .isNull(ChartFiles::getParentId)
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        } else {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .eq(ChartFiles::getParentId, chartFiles.getParentId())
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        }
        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("文件夹名称重复");
        }

        // 设置用户ID并保存或更新文件夹信息
        chartFiles.setUserId(SecurityUtils.getUserId());
        boolean result = chartFilesService.saveOrUpdate(chartFiles);

        // 如果保存或更新成功，更新缓存
        if (result) {

            // 更新缓存
            // deleteRedisAllkeyByUserId();
            return AjaxResult.success();
        }

        return AjaxResult.error();
    }


    @ApiOperation("文件夹：编辑")
    @PostMapping("/user/edit")
    @Transactional
    public AjaxResult edit(@RequestBody ChartFiles chartFiles) {
        if (ObjectUtils.isEmpty(chartFiles.getFileName())) {
            return AjaxResult.error("请填写文件夹名称");
        }

        // 检查是否存在重复文件夹名称，排除自身
        ChartFiles one;
        if (chartFiles.getParentId() == null) {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .isNull(ChartFiles::getParentId)
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        } else {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .eq(ChartFiles::getParentId, chartFiles.getParentId())
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        }
        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("文件夹名称重复");
        }

        // 保存或更新文件夹信息
        boolean result = chartFilesService.saveOrUpdate(chartFiles);
        if (result) {
            // deleteRedisAllkeyByUserId(); // 更新缓存
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 更新缓存，删除与文件夹名称相关的缓存并可选地添加修改后的文件夹信息到缓存中
     */
/*    private void updateCache(ChartFiles chartFiles) {
        Long userId = SecurityUtils.getUserId();

        // 删除与文件夹名称相关的缓存
        String keyPattern = "getInfoByName:" + userId + ":*";
        redisCache.deleteByPattern(keyPattern);

        // 清除通用缓存（所有名称的缓存）
        String allKey = "getInfoByName:" + userId + ":all";
        redisCache.deleteObject(allKey);

        // 可以根据需要将修改后的文件夹信息添加到缓存中
        // 比如：redisCache.setCacheObject("folder:" + chartFiles.getId(), chartFiles);
    }*/

/*    @ApiOperation("文件夹：编辑")
    @PostMapping("/user/edit")
    @Transactional
    public AjaxResult edit(@RequestBody ChartFiles chartFiles) {
        if (ObjectUtils.isEmpty(chartFiles.getFileName())) {
            return AjaxResult.error("请填写文件夹名称");
        }

        ChartFiles one;
        if (chartFiles.getParentId() == null) {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .isNull(ChartFiles::getParentId)
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        } else {
            one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>()
                    .eq(ChartFiles::getParentId, chartFiles.getParentId())
                    .eq(ChartFiles::getUserId, SecurityUtils.getUserId())
                    .eq(ChartFiles::getFileName, chartFiles.getFileName()));
        }
        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("文件夹名称重复");
        }

        boolean result = chartFilesService.saveOrUpdate(chartFiles);
        if (result) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }*/
    @ApiOperation("文件夹：图表/大屏移动")
    @PostMapping("/user/move")
    @Transactional
    public AjaxResult edit(@RequestBody ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
        if (chartConfigsAndViewsVo.getChartModeType() == 1) {
            ChartConfigsUser one = null;
            //判断图表名称是否会重复
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
                one = chartConfigsUserService.getOne(new LambdaQueryWrapper<ChartConfigsUser>().isNull(ChartConfigsUser::getFileId)
                        .eq(ChartConfigsUser::getUserId, SecurityUtils.getUserId()).eq(ChartConfigsUser::getChartName, chartConfigsAndViewsVo.getName()));
            } else {
                one = chartConfigsUserService.getOne(new LambdaQueryWrapper<ChartConfigsUser>().eq(ChartConfigsUser::getFileId, chartConfigsAndViewsVo.getFileId())
                        .eq(ChartConfigsUser::getUserId, SecurityUtils.getUserId()).eq(ChartConfigsUser::getChartName, chartConfigsAndViewsVo.getName()));
            }

            if (!ObjectUtils.isEmpty(one)) {
                return AjaxResult.error("图表名重复");
            }
            one = new ChartConfigsUser();
            one.setId(chartConfigsAndViewsVo.getId());
            one.setFileId(chartConfigsAndViewsVo.getFileId());
            boolean result = chartConfigsUserService.updateConfigTop(one);
            if (result) {
                return AjaxResult.success();
            }
        } else {
            ChartViewsUser one = null;
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
                one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().isNull(ChartViewsUser::getFileId)
                        .eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()).eq(ChartViewsUser::getViewName, chartConfigsAndViewsVo.getName()));
            } else {
                one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getFileId, chartConfigsAndViewsVo.getFileId())
                        .eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()).eq(ChartViewsUser::getViewName, chartConfigsAndViewsVo.getName()));
            }


            if (!ObjectUtils.isEmpty(one)) {
                return AjaxResult.error("图表名重复");
            }
            one = new ChartViewsUser();
            one.setId(chartConfigsAndViewsVo.getId());
            one.setFileId(chartConfigsAndViewsVo.getFileId());

            boolean result = chartViewsUserService.updateViewTop(one);

            if (result) {
                return AjaxResult.success();
            }
        }

        return AjaxResult.error();
    }


    @ApiOperation("文件夹：移动并创建副本")
    @PostMapping("/user/moveAndcopy")
    @Transactional
    public AjaxResult moveAndcopy(@RequestBody ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
//        if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getCopyName())) {
//            return AjaxResult.error("请填写文件夹名称");
//        }
        chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());
        List<ChartConfigsAndViewsVo> configsAndViewsVoList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);

        if (!ObjectUtils.isEmpty(configsAndViewsVoList)) {
            return AjaxResult.error("文件夹名称重复");
        }

        boolean result = false;
        if (chartConfigsAndViewsVo.getChartModeType() == 1) {
            ChartConfigsUser configsUser = chartConfigsUserService.getById(chartConfigsAndViewsVo.getId());
            ChartConfigsUser chartConfigsUser = new ChartConfigsUser();
            BeanUtils.copyProperties(configsUser, chartConfigsUser);
            configsUser.setFileId(chartConfigsAndViewsVo.getFileId());
            chartConfigsUser.setId(null);

            List<ChartConfigsUser> list = new ArrayList<>();
            list.add(configsUser);
            list.add(chartConfigsUser);
            result = chartConfigsUserService.saveOrUpdateBatch(list);
        } else {
            ChartViewsUser viewsUser = chartViewsUserService.getById(chartConfigsAndViewsVo.getId());
            ChartViewsUser chartViewsUser = new ChartViewsUser();
            BeanUtils.copyProperties(viewsUser, chartViewsUser);
            viewsUser.setFileId(chartConfigsAndViewsVo.getFileId());
            chartViewsUser.setId(null);

            List<ChartViewsUser> list = new ArrayList<>();
            list.add(viewsUser);
            list.add(chartViewsUser);
            result = chartViewsUserService.saveOrUpdateBatch(list);
        }

        if (result) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }


    @ApiOperation("创建图表/大屏副本")
    @PostMapping("/user/copy")
    @Transactional
    public AjaxResult copy(@RequestBody ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
        if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getCopyName()) || ObjectUtils.isEmpty(chartConfigsAndViewsVo.getId())) {
            return AjaxResult.error();
        }


        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.queryById(userId);
        Integer isVip = sysUser.getIsVip();
        if (isVip == 0) { //不是VIP
            int seatCountNumber = userCoinLogsService.querySeatCount();//总席位数量// 查询席位的数量

            LambdaQueryWrapper<ChartConfigsUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ChartConfigsUser::getUserId, userId);
            List<ChartConfigsUser> chartConfigsUsers = chartConfigsUserService.list(lqw);
            int size = chartConfigsUsers.size(); //已经使用的席位 //查询保存到我的生成的数量
            if (seatCountNumber <= size) {
                return AjaxResult.error(CUSTOM_ERROR, "保存文件数不足，请充值");
            }
        }

        boolean b = false;
        if (chartConfigsAndViewsVo.getChartModeType() == 1) {
            ChartConfigsUser chartConfigsUser = null;
            if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
                chartConfigsUser = chartConfigsUserService.getOne(new LambdaQueryWrapper<ChartConfigsUser>().eq(ChartConfigsUser::getFileId, chartConfigsAndViewsVo.getFileId()).
                        eq(ChartConfigsUser::getChartName, chartConfigsAndViewsVo.getCopyName()));
            } else {
                chartConfigsUser = chartConfigsUserService.getOne(new LambdaQueryWrapper<ChartConfigsUser>().isNull(ChartConfigsUser::getFileId)
                        .eq(ChartConfigsUser::getChartName, chartConfigsAndViewsVo.getCopyName()));
            }

            if (ObjectUtils.isEmpty(chartConfigsUser)) {
                ChartConfigsUser configsUser = chartConfigsUserService.getById(chartConfigsAndViewsVo.getId());
                configsUser.setChartName(chartConfigsAndViewsVo.getCopyName());
                configsUser.setId(null);
                configsUser.setFileId(chartConfigsAndViewsVo.getFileId());
                b = chartConfigsUserService.saveOrUpdate(configsUser);

                if (b) {
                    return AjaxResult.success(configsUser.getId());
                }
            } else {

                // return AjaxResult.error("图表名称重复", map);
                return AjaxResult.error(CUSTOM_EXCEPTION_CODE,"创建副本图表名称重复，请改名后重试");

            }

        } else {
            ChartViewsUser chartViewsUser = null;
            if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
                chartViewsUser = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getFileId, chartConfigsAndViewsVo.getFileId()).
                        eq(ChartViewsUser::getViewName, chartConfigsAndViewsVo.getName()));
            } else {
                chartViewsUser = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().isNull(ChartViewsUser::getFileId)
                        .eq(ChartViewsUser::getViewName, chartConfigsAndViewsVo.getName()));
            }

            if (ObjectUtils.isEmpty(chartViewsUser)) {
                ChartViewsUser viewsUser = chartViewsUserService.getById(chartConfigsAndViewsVo.getId());
                viewsUser.setViewName(chartConfigsAndViewsVo.getCopyName());
                viewsUser.setId(null);
                viewsUser.setFileId(chartConfigsAndViewsVo.getFileId());
                b = chartViewsUserService.saveOrUpdate(viewsUser);

                if (b) {
                    return AjaxResult.success(viewsUser.getId());
                }
            } else {
                return AjaxResult.error("大屏名称重复");
            }
        }
        return AjaxResult.error();
    }

    @ApiOperation("文件夹：根据id获取文件夹详情")
    @GetMapping("/user/getInfo")
    public AjaxResult getInfo(ChartFiles chartFiles) {
        ChartFiles one = chartFilesService.getOne(new LambdaQueryWrapper<ChartFiles>().eq(ChartFiles::getFileId, chartFiles.getFileId()));
        return AjaxResult.success(one);
    }


    @ApiOperation("文件夹：根据id获取文件夹图表/大屏")
    @GetMapping("/user/getCharts")
    public AjaxResult getCharts(ChartConfigsUser chartConfigsUser) {
        chartConfigsUser.setUserId(SecurityUtils.getUserId());
        List<Long> ids = new ArrayList<>();
        ids.add(chartConfigsUser.getFileId());
        List<ChartConfigsAndViewsVo> list = chartConfigsUserService.getChartsAndViewsBathByFileIds(ids);
        return AjaxResult.success(list);
    }

/*    public void deleteRedisAllkeyByUserId() {
        Long userId = SecurityUtils.getUserId();
        String cacheKeyPattern = CacheConstants.CHART_USER_CONFIGS_KEY + userId + ":*";
        redisCache.deleteObject(cacheKeyPattern);

        try {
            Set<String> keys = redisTemplate.keys(cacheKeyPattern);
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                logger.info("Cache keys deleted: " + keys);
            } else {
                logger.info("No cache keys found matching pattern: " + cacheKeyPattern);
            }
        } catch (Exception e) {
            logger.error("Error occurred while deleting cache keys: ", e);
        }
    }*/


    @ApiOperation("文件夹：根据id删除")
    @PostMapping("/user/del")
    @Transactional
    public AjaxResult del(@RequestBody ChartFiles chartFiles) {
        // 获取到这个文件夹所有的下级目录和上一级目录
        List<Long> ids = getIds(chartFiles.getFileId());

        if (!CollectionUtils.isEmpty(ids)) {
            boolean a = chartFilesService.removeByIds(ids);
            if (a) {
                List<Long> fileids = new ArrayList<>();
                for (Long id : ids) {
                    List<ChartConfigsUser> list = chartConfigsUserService.list(new LambdaQueryWrapper<ChartConfigsUser>()
                            .eq(ChartConfigsUser::getFileId, id)
                            .eq(ChartConfigsUser::getUserId, SecurityUtils.getUserId()));
                    if (!CollectionUtils.isEmpty(list)) {
                        fileids.add(id);
                    }
                }

                if (!CollectionUtils.isEmpty(fileids)) {
                    List<ChartConfigsUser> configsUserList = chartConfigsUserService.list(new LambdaQueryWrapper<ChartConfigsUser>()
                            .in(ChartConfigsUser::getFileId, fileids));
                    if (!CollectionUtils.isEmpty(configsUserList)) {
                        boolean b = chartConfigsUserService.remove(new LambdaQueryWrapper<ChartConfigsUser>()
                                .in(ChartConfigsUser::getFileId, fileids));
                        if (b) {
                            List<ChartViewsUser> viewsUserList = chartViewsUserService.list(new LambdaQueryWrapper<ChartViewsUser>()
                                    .in(ChartViewsUser::getFileId, fileids));
                            if (!CollectionUtils.isEmpty(viewsUserList)) {
                                boolean c = chartViewsUserService.remove(new LambdaQueryWrapper<ChartViewsUser>()
                                        .in(ChartViewsUser::getFileId, fileids));
                                if (c) {
                                    //操作缓存
                                    // deleteRedisAllkeyByUserId();
                                    return AjaxResult.success();
                                }
                            } else {
                                //操作缓存
                                // deleteRedisAllkeyByUserId();
                                return AjaxResult.success();
                            }
                        }
                    } else {
                        List<ChartViewsUser> viewsUserList = chartViewsUserService.list(new LambdaQueryWrapper<ChartViewsUser>()
                                .in(ChartViewsUser::getFileId, fileids));
                        if (!CollectionUtils.isEmpty(viewsUserList)) {
                            boolean c = chartViewsUserService.remove(new LambdaQueryWrapper<ChartViewsUser>()
                                    .in(ChartViewsUser::getFileId, fileids));
                            if (c) {
                                //操作缓存
                                // deleteRedisAllkeyByUserId();
                                return AjaxResult.success();
                            }
                        }
                    }

                } else {
                    //操作缓存
                    // deleteRedisAllkeyByUserId();
                    return AjaxResult.success();
                }

            }

        }
        return AjaxResult.error();
    }


/*    @ApiOperation("文件夹：根据id删除")
    @PostMapping("/user/del")
    @Transactional
    public AjaxResult del(@RequestBody ChartFiles chartFiles) {
        // 获取到这个文件夹所有的下级目录和上一级目录
        List<Long> ids = getIds(chartFiles.getFileId());

        if (!CollectionUtils.isEmpty(ids)) {
            boolean a = chartFilesService.removeByIds(ids);
            if (a) {
                List<Long> fileids = new ArrayList<>();
                for (int i = 0; i < ids.size(); i++) {
                    Long aLong = ids.get(i);
                    List<ChartConfigsUser> list = chartConfigsUserService.list(new LambdaQueryWrapper<ChartConfigsUser>()
                            .eq(ChartConfigsUser::getFileId, aLong)
                            .eq(ChartConfigsUser::getUserId, SecurityUtils.getUserId()));
                    if (!CollectionUtils.isEmpty(list)) {
                        fileids.add(aLong);
                    }
                }

                if (!CollectionUtils.isEmpty(fileids)) {
                    List<ChartConfigsUser> configsUserList = chartConfigsUserService.list(new LambdaQueryWrapper<ChartConfigsUser>()
                            .in(ChartConfigsUser::getFileId, fileids));
                    if (!CollectionUtils.isEmpty(configsUserList)) {
                        boolean b = chartConfigsUserService.remove(new LambdaQueryWrapper<ChartConfigsUser>()
                                .in(ChartConfigsUser::getFileId, fileids));
                        if (b) {
                            List<ChartViewsUser> viewsUserList = chartViewsUserService.list(new LambdaQueryWrapper<ChartViewsUser>()
                                    .in(ChartViewsUser::getFileId, fileids));
                            if (!CollectionUtils.isEmpty(viewsUserList)) {
                                boolean c = chartViewsUserService.remove(new LambdaQueryWrapper<ChartViewsUser>()
                                        .in(ChartViewsUser::getFileId, fileids));
                                if (c) {
                                    updateCache(chartFiles.getFileId());
                                    return AjaxResult.success();
                                }
                            } else {
                                updateCache(chartFiles.getFileId());
                                return AjaxResult.success();
                            }
                        }
                    } else {
                        List<ChartViewsUser> viewsUserList = chartViewsUserService.list(new LambdaQueryWrapper<ChartViewsUser>()
                                .in(ChartViewsUser::getFileId, fileids));
                        if (!CollectionUtils.isEmpty(viewsUserList)) {
                            boolean c = chartViewsUserService.remove(new LambdaQueryWrapper<ChartViewsUser>()
                                    .in(ChartViewsUser::getFileId, fileids));
                            if (c) {
                                updateCache(chartFiles.getFileId());
                                return AjaxResult.success();
                            }
                        }
                    }

                } else {
                    updateCache(chartFiles.getFileId());
                    return AjaxResult.success();
                }

            }

        }
        return AjaxResult.error();
    }*/

/*    private void updateCache(Long fileId) {
        Long userId = SecurityUtils.getUserId();
        String keyPattern = "getInfoByName:" + userId + ":*";
        redisCache.deleteByPattern(keyPattern);

        // 清除与删除文件相关的缓存
        String specificKey = "getInfoByName:" + userId + ":" + fileId;
        redisCache.deleteObject(specificKey);

        // 清除通用缓存（所有名称的缓存）
        String allKey = "getInfoByName:" + userId + ":all";
        redisCache.deleteObject(allKey);
    }

    // 假设getIds方法的定义如下
    private List<Long> getIds(Long fileId) {
        // 实现获取所有相关的下级目录和上一级目录的ID
        // 此处略去具体实现
        return new ArrayList<>();
    }*/

/*
    @ApiOperation("文件夹：根据id删除")
    @PostMapping("/user/del")
    @Transactional
    public AjaxResult del(@RequestBody ChartFiles chartFiles) {
        //获取到这个文件夹所有的下级目录和上一级目录
        List<Long> ids = getIds(chartFiles.getFileId());

        if (!CollectionUtils.isEmpty(ids)) {
            boolean a = chartFilesService.removeByIds(ids);
            if (a) {
                List<Long> fileids = new ArrayList<>();
                for (int i = 0; i < ids.size(); i++) {
                    Long aLong = ids.get(i);
                    List<ChartConfigsUser> list = chartConfigsUserService.list(new LambdaQueryWrapper<ChartConfigsUser>().eq(ChartConfigsUser::getFileId, aLong)
                            .eq(ChartConfigsUser::getUserId, SecurityUtils.getUserId()));
                    if (!CollectionUtils.isEmpty(list)) {
                        fileids.add(aLong);
                    }
                }


                if (!CollectionUtils.isEmpty(fileids)) {
                    List<ChartConfigsUser> configsUserList = chartConfigsUserService.list(new LambdaQueryWrapper<ChartConfigsUser>().in(ChartConfigsUser::getFileId, fileids));
                    if (!CollectionUtils.isEmpty(configsUserList)) {
                        boolean b = chartConfigsUserService.remove(new LambdaQueryWrapper<ChartConfigsUser>().in(ChartConfigsUser::getFileId, fileids));
                        if (b) {
                            List<ChartViewsUser> viewsUserList = chartViewsUserService.list(new LambdaQueryWrapper<ChartViewsUser>().in(ChartViewsUser::getFileId, fileids));
                            if (!CollectionUtils.isEmpty(viewsUserList)) {
                                boolean c = chartViewsUserService.remove(new LambdaQueryWrapper<ChartViewsUser>().in(ChartViewsUser::getFileId, fileids));
                                if (c) {
                                    return AjaxResult.success();
                                }
                            } else {

                                return AjaxResult.success();
                            }
                        }
                    } else {
                        List<ChartViewsUser> viewsUserList = chartViewsUserService.list(new LambdaQueryWrapper<ChartViewsUser>().in(ChartViewsUser::getFileId, fileids));
                        if (!CollectionUtils.isEmpty(viewsUserList)) {
                            boolean c = chartViewsUserService.remove(new LambdaQueryWrapper<ChartViewsUser>().in(ChartViewsUser::getFileId, fileids));
                            if (c) {

                                return AjaxResult.success();
                            }
                        }
                    }

                } else {

                    return AjaxResult.success();
                }

            }


        }
        return AjaxResult.error();
    }
*/


    @ApiOperation("文件夹：打散文件")
    @PostMapping("/user/scatter")
    @Transactional
    public AjaxResult scatter(@RequestBody ChartFiles chartFiles) {
        List<Long> ids = getIds(chartFiles.getFileId());

        if (CollectionUtils.isEmpty(ids)) {
            return AjaxResult.error("不存在该文件夹");
        }
        //获取该用户下所有的文件夹和大屏
        List<ChartConfigsAndViewsVo> list = chartConfigsUserService.getChartsAndViewsBathByFileIds(ids);

        if (!CollectionUtils.isEmpty(list)) {

            boolean a = false;
            boolean b = false;

            //将信息进行分类
            Map<Integer, List<ChartConfigsAndViewsVo>> map = list.stream()
                    .collect(Collectors.groupingBy(ChartConfigsAndViewsVo::getChartModeType));
            //判断文件夹打散后，当前文件夹中文件是否重复
            if (!CollectionUtils.isEmpty(map.get(1))) {
                List<ChartConfigsAndViewsVo> configUserList = map.get(1);
                List<String> collect1 = configUserList.stream().map(ChartConfigsAndViewsVo::getName).collect(Collectors.toList());
                List<ChartConfigsUser> oldList = chartConfigsUserService.list(new LambdaQueryWrapper<ChartConfigsUser>().in(ChartConfigsUser::getChartName, collect1).
                        eq(ChartConfigsUser::getUserId, SecurityUtils.getUserId()).isNull(ChartConfigsUser::getFileId));
                if (!CollectionUtils.isEmpty(oldList)) {
                    List<String> collect2 = oldList.stream().map(ChartConfigsUser::getChartName).collect(Collectors.toList());
                    return AjaxResult.error(collect2 + "文件夹内图表、大屏名称和外部重复");
                }
                List<ChartConfigsUser> collect = configUserList.stream().map(e -> {
                    ChartConfigsUser user = new ChartConfigsUser();
                    user.setId(e.getId());
                    user.setFileId(null);
                    return user;
                }).collect(Collectors.toList());
                a = chartConfigsUserService.scatterChartfigsUser(collect);
//                    a = chartConfigsUserService.saveOrUpdateBatch(collect);
            }
            if (!CollectionUtils.isEmpty(map.get(2))) {
                List<ChartConfigsAndViewsVo> viewUserList = map.get(2);
                List<String> collect1 = viewUserList.stream().map(ChartConfigsAndViewsVo::getName).collect(Collectors.toList());
                List<ChartViewsUser> oldList = chartViewsUserService.list(new LambdaQueryWrapper<ChartViewsUser>().in(ChartViewsUser::getViewName, collect1).
                        eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()).isNull(ChartViewsUser::getFileId));
                if (!CollectionUtils.isEmpty(oldList)) {
                    List<String> collect2 = oldList.stream().map(ChartViewsUser::getViewName).collect(Collectors.toList());
                    return AjaxResult.error(collect2 + "文件夹内图表、大屏名称和外部重复");
                }
                List<ChartViewsUser> collect = viewUserList.stream().map(e -> {
                    ChartViewsUser user = new ChartViewsUser();
                    user.setId(e.getId());
                    user.setFileId(null);
                    return user;
                }).collect(Collectors.toList());
                b = chartViewsUserService.scatterChartViewUser(collect);
//                    b = chartViewsUserService.saveOrUpdateBatch(collect);
            }
            if (!CollectionUtils.isEmpty(map.get(1))) {
                if (!CollectionUtils.isEmpty(map.get(2))) {
                    if (b && a) {
                        return AjaxResult.success();
                    }
                } else {
                    if (a) {
                        return AjaxResult.success();
                    }
                }
            } else {
                if (!CollectionUtils.isEmpty(map.get(2))) {
                    if (b) {
                        return AjaxResult.success();
                    }
                }
            }
        } else {
            return AjaxResult.success("该文件夹不存在图表、大屏");
        }
        return AjaxResult.error();
    }

    /*    @ApiOperation("文件夹：根据名称筛选不加缓存")
        @GetMapping("/user/list")
        @Transactional
        public AjaxResult getInfoByName(ChartConfigsAndViewsVo chartConfigsAndViewsVo)
        {
            chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());

            List<ChartConfigsAndViewsVo> list = new ArrayList<>();

            //文件夹、图表、大屏的多表联合   进行根据名称进行筛选
            if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
                List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles(chartConfigsAndViewsVo);
                list.addAll(fileList);
                List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);
                list.addAll(cAvList);
            } else {
                list = chartConfigsUserService.getInfoByName(chartConfigsAndViewsVo);
                if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getName())) {
                    list = list.stream().filter(e -> ObjectUtils.isEmpty(e.getParentId()) || ObjectUtils.isEmpty(e.getFileId())).collect(Collectors.toList());
                }
            }

            return AjaxResult.success(list);
        }*/





/*

    @ApiOperation("文件夹：根据名称筛选")
    @GetMapping("/user/list")
    @Transactional
    public AjaxResult getInfoByName(ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
        chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());

        // 使用 userId, name 和 fileId 作为缓存键的组成部分，确保唯一性
        String nameKey = chartConfigsAndViewsVo.getName() != null ? chartConfigsAndViewsVo.getName() : "all";
        String fileIdKey = chartConfigsAndViewsVo.getFileId() != null ? chartConfigsAndViewsVo.getFileId().toString() : "noFileId";
        String key = CacheConstants.CHART_USER_CONFIGS_KEY + SecurityUtils.getUserId() + ":" + nameKey + ":" + fileIdKey;

        // 先从缓存中获取数据
        List<ChartConfigsAndViewsVo> list = redisCache.getCacheList(key);

        if (list != null && !list.isEmpty()) {
            return AjaxResult.success(list);
        }
        list = new ArrayList<>();
        // 文件夹、图表、大屏的多表联合 根据名称进行筛选
        if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
            List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles(chartConfigsAndViewsVo);
            list.addAll(fileList);
            List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);
            list.addAll(cAvList);
        } else {
            list = chartConfigsUserService.getInfoByName(chartConfigsAndViewsVo);
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getName())) {
                list = list.stream().filter(e -> ObjectUtils.isEmpty(e.getParentId()) || ObjectUtils.isEmpty(e.getFileId())).collect(Collectors.toList());
            }
        }
        redisCache.setCacheListTwo(key, list, 10, TimeUnit.MINUTES); // 缓存 10 分钟
        return AjaxResult.success(list);
    }
*/




/*    @ApiOperation("文件夹：根据名称筛选加了缓存")
    @GetMapping("/user/list")
    @Transactional
    public AjaxResult getInfoByName(ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
        chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());

    *//*    // 使用 userId, name 和 fileId 作为缓存键的组成部分，确保唯一性
        String nameKey = chartConfigsAndViewsVo.getName() != null ? chartConfigsAndViewsVo.getName() : "all";
        String fileIdKey = chartConfigsAndViewsVo.getFileId() != null ? chartConfigsAndViewsVo.getFileId().toString() : "noFileId";

         String key = CacheConstants.CHART_USER_CONFIGS_KEY + SecurityUtils.getUserId() + ":" + nameKey + ":" + fileIdKey;

*//*
        // 生成一个介于0（包括）和100（不包括）之间的随机长整数
        long randomLong = RandomUtils.nextLong(0, 1000);
        int randomInt = RandomUtils.nextInt(0, 1000);
        String key = CacheConstants.CHART_USER_CONFIGS_KEY + SecurityUtils.getUserId() + ":" + randomLong + randomInt;
        //String key = CacheConstants.CHART_USER_CONFIGS_KEY + SecurityUtils.getUserId() +  ":*";
        // 先从缓存中获取数据
        List<ChartConfigsAndViewsVo> list = redisCache.getCacheObject(key);

        if (list != null && !list.isEmpty()) {
            return AjaxResult.success(list);
        }

        list = new ArrayList<>();

        // 文件夹、图表、大屏的多表联合 根据名称进行筛选
        if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
            List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles(chartConfigsAndViewsVo);
            list.addAll(fileList);
            List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);
            list.addAll(cAvList);
        } else {
            list = chartConfigsUserService.getInfoByName(chartConfigsAndViewsVo);
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getName())) {
                list = list.stream().filter(e -> ObjectUtils.isEmpty(e.getParentId()) || ObjectUtils.isEmpty(e.getFileId())).collect(Collectors.toList());
            }
        }

        // 将数据缓存 10 分钟
        redisCache.setCacheObject(key, list, 10, TimeUnit.MINUTES);

        return AjaxResult.success(list);
    }*/


    @RequestMapping("download")
    public void download(@Param("source") String source, HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File(source);
        if (file == null || !file.exists()) {
            throw new FileNotFoundException("请求的文件不存在");
        }
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            String agent = (String) request.getHeader("USER-AGENT");
            String fileName = file.getName();
            if (agent != null && agent.indexOf("MSIE") == -1) {
// FF
                String enableFileName = "=?UTF-8?B?" + (new String(Base64.getEncoder().encode(fileName.getBytes("UTF-8")))) + "?=";
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
            } else {
// IE
                String enableFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
            }
//			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            out = response.getOutputStream();
            out.write(org.apache.commons.io.FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String convertImageToBase64(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        try (InputStream is = url.openStream()) {
            byte[] bytes = IOUtils.toByteArray(is);
            return Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            // 处理读取URL的异常，可以记录日志或重新抛出
            throw new IOException("Failed to convert image to Base64", e);
        }
    }

    @ApiOperation("文件夹：根据名称筛选")
    @GetMapping("/user/list/demo111111")
    @Transactional
    public AjaxResult getInfoByNameDemo(ChartConfigsAndViewsVo chartConfigsAndViewsVo) throws IOException {

        String imageUrl = chartConfigsAndViewsVo.getImageUrl();
        String url = "http://localhost:10003/file/download?source=C:/Users/Administrator/Desktop/upload/" + "chartCover_8175012662.png";
        String base = convertImageToBase64(url);
        String base64 = "data:image/png;base64," + base;
        List<ChartConfigsAndViewsVo> infoByName1 = chartConfigsUserService.getInfoByName1(chartConfigsAndViewsVo);
        for (ChartConfigsAndViewsVo configsAndViewsVo : infoByName1) {
            System.out.println(configsAndViewsVo);
        }
        System.out.println(base64);
        return AjaxResult.success();
    }

/*  7.23  @ApiOperation("文件夹：根据名称筛选")
    @GetMapping("/user/list")
    @Transactional
    public AjaxResult getInfoByName(ChartConfigsAndViewsVo chartConfigsAndViewsVo) throws IOException {
        chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());

        List<ChartConfigsAndViewsVo> list = new ArrayList<>();
        // 文件夹、图表、大屏的多表联合进行根据名称进行筛选
        if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
            List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles(chartConfigsAndViewsVo);
           // List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles1(chartConfigsAndViewsVo);
            list.addAll(fileList);
            List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);
          //  List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch1(chartConfigsAndViewsVo);
            list.addAll(cAvList);
        } else {
            list = chartConfigsUserService.getInfoByName(chartConfigsAndViewsVo);
            // list = chartConfigsUserService.getInfoByName1(chartConfigsAndViewsVo);
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getName())) {
                List<ChartConfigsAndViewsVo> filteredList = new ArrayList<>();
                for (ChartConfigsAndViewsVo item : list) {
                    if (ObjectUtils.isEmpty(item.getParentId()) || ObjectUtils.isEmpty(item.getFileId())) {
                        filteredList.add(item);
                    }
                }
                list = filteredList;
            }

        }


*//*
        // 遍历查询出来的结果，获取里的image_url然后读取照片地址并转换为base64
        for (ChartConfigsAndViewsVo item : list) {
                String imageUrl =item.getImageUrl();

                String url = "http://localhost:10003/file/download?source=C:/Users/Administrator/Desktop/upload/" + imageUrl;
                String base = convertImageToBase64(url);
                String  base64 ="data:image/png;base64,"+ base;
               item.setImageBase64(base64);
                item.setImageUrl(imageUrl);

        }*//*

        return AjaxResult.success(list);
    }*/


    @ApiOperation("文件夹：根据名称筛选")
    @GetMapping("/user/list")
    @Transactional
    public HashMap<Object, Object> getInfoByName(ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
        chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());
        List<ChartConfigsAndViewsVo> list = new ArrayList<>();

        //文件夹、图表、大屏的多表联合   进行根据名称进行筛选
        if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
            List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles(chartConfigsAndViewsVo);
            list.addAll(fileList);
            List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);
            list.addAll(cAvList);
        } else {
            list = chartConfigsUserService.getInfoByName(chartConfigsAndViewsVo);
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getName())) {
                list = list.stream().filter(e -> ObjectUtils.isEmpty(e.getParentId()) || ObjectUtils.isEmpty(e.getFileId())).collect(Collectors.toList());
            }
        }

        //查询已用席位
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ChartConfigsUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ChartConfigsUser::getUserId, userId);
        List<ChartConfigsUser> chartConfigsUsers = chartConfigsUserService.list(lqw);
        int size = chartConfigsUsers.size();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("msg", "操作成功");
        map.put("code", 200);
        map.put("data", list);
        map.put("total", size);
        return map;
    }


    /**
     * 7.22
     * @param chartConfigsAndViewsVo
     * @return
     */
/*    @ApiOperation("文件夹：根据名称筛选")
    @GetMapping("/user/list")
    @Transactional
    public AjaxResult getInfoByName(ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
        chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());
        // 使用 userId, name 和 fileId 作为缓存键的组成部分，确保唯一性
        String nameKey = chartConfigsAndViewsVo.getName() != null ? chartConfigsAndViewsVo.getName() : "all";
        String fileIdKey = chartConfigsAndViewsVo.getFileId()!= null ? chartConfigsAndViewsVo.getFileId().toString() : "noFileId";
        String key = CacheConstants.CHART_USER_CONFIGS_KEY + SecurityUtils.getUserId() + ":" + nameKey + ":" + fileIdKey;
        // 先从缓存中获取数据

        List<ChartConfigsAndViewsVo> list = redisCache.getCacheObject(key);
        if (list != null && !list.isEmpty()) {
            return AjaxResult.success(list);
        }
        list = new ArrayList<>();
        // 文件夹、图表、大屏的多表联合 根据名称进行筛选
        if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
            List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles(chartConfigsAndViewsVo);
            list.addAll(fileList);
            List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);
            list.addAll(cAvList);
        } else {
            list = chartConfigsUserService.getInfoByName(chartConfigsAndViewsVo);
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getName())) {
                list = list.stream().filter(e -> ObjectUtils.isEmpty(e.getParentId()) || ObjectUtils.isEmpty(e.getFileId())).collect(Collectors.toList());
            }
        }
        redisCache.setCacheObject(key, list, 10, TimeUnit.MINUTES); // 缓存 10 分钟

        return AjaxResult.success(list);
    }*/



/*    //7.19
    @ApiOperation("文件夹：根据名称筛选")
    @GetMapping("/user/list")
    @Transactional
    public AjaxResult getInfoByName(ChartConfigsAndViewsVo chartConfigsAndViewsVo) {
        chartConfigsAndViewsVo.setUserId(SecurityUtils.getUserId());

        // 使用 userId, name 和 fileId 作为缓存键的组成部分，确保唯一性
        // 使用 CacheConstants 中的常量构建缓存键
        String nameKey = chartConfigsAndViewsVo.getName() != null ? chartConfigsAndViewsVo.getName() : "all";
        String fileIdKey = chartConfigsAndViewsVo.getFileId() != null ? chartConfigsAndViewsVo.getFileId().toString() : "noFileId";
        String key = CacheConstants.USER_CHART_CONFIGS_KEY + SecurityUtils.getUserId() + ":" + nameKey + ":" + fileIdKey;

        // 先从缓存中获取数据
        List<ChartConfigsAndViewsVo> list = redisCache.getCacheList(key);

        if (list != null && !list.isEmpty()) {
            return AjaxResult.success(list);
        }
        list = new ArrayList<>();
        // 文件夹、图表、大屏的多表联合 根据名称进行筛选
        if (!ObjectUtils.isEmpty(chartConfigsAndViewsVo.getFileId())) {
            List<ChartConfigsAndViewsVo> fileList = chartConfigsUserService.getFiles(chartConfigsAndViewsVo);
            list.addAll(fileList);
            List<ChartConfigsAndViewsVo> cAvList = chartConfigsUserService.getChartsAndViewsBatch(chartConfigsAndViewsVo);
            list.addAll(cAvList);
        } else {
            list = chartConfigsUserService.getInfoByName(chartConfigsAndViewsVo);
            if (ObjectUtils.isEmpty(chartConfigsAndViewsVo.getName())) {
                list = list.stream().filter(e -> ObjectUtils.isEmpty(e.getParentId()) || ObjectUtils.isEmpty(e.getFileId())).collect(Collectors.toList());
            }
        }
        redisCache.setCacheListTwo(key, list, 10, TimeUnit.MINUTES); // 缓存 10 分钟
        return AjaxResult.success(list);
    }*/


    /**
     * 专家图例的查询接口
     *
     * @param userId
     * @param chartName
     * @param chartType
     * @param subjectId
     * @param configId
     * @param sortOrder
     * @return
     */
    @GetMapping("/user/v2/list")
    public AjaxResult v4getInfoByName(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "chartName", required = false) String chartName,
            @RequestParam(value = "chartType", required = false) String chartType,
            @RequestParam(value = "subjectType", required = false) Long subjectId,
            @RequestParam(value = "configId", required = false) Long configId,
            @RequestParam(value = "sortOrder", required = false, defaultValue = "0") Long sortOrder) {
        // 直接从数据库中获取数据
        List<ChartConfigsUser> list = chartConfigsUserService.getUsersExcludingChartValue(userId, chartName, chartType, subjectId, configId, sortOrder);
        return AjaxResult.success(list);
    }


    /**
     * 专家图例的查询 查询之后渲染
     * 给ai 用
     *
     * @return
     */
    //  @PostMapping("/ai/expert/chart/list")
    public AjaxResult queryExpertChartList(@RequestBody ChartDateTto chartDateTto) throws Exception {
        if (chartDateTto.getDataList() == null) {
            return AjaxResult.error("输入数据无效");
        }
        Long subjectId = chartDateTto.getSubjectId();
        Integer chartType = chartDateTto.getChartTypeList().get(0);
        LambdaQueryWrapper<ChartConfigsUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ChartConfigsUser::getUserId, 2);
        lqw.eq(ChartConfigsUser::getStatus, 0);
        lqw.eq(ChartConfigsUser::getChartType, chartDateTto.getChartTypeList().get(0));
        if (subjectId != null) {
            lqw.eq(ChartConfigsUser::getSubjectId, subjectId);
        }
        List<ChartConfigsUser> list = chartConfigsUserService.list(lqw);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.error("未找到图表配置");
        }
        if (chartType == 1) {
            ArrayList<ChartSmartVo> newLista = new ArrayList<>();
            for (ChartConfigsUser chartConfigsUser : list) {

                List<List<String>> data = extractDataFromList(chartDateTto.getDataList());
                String configValue = chartConfigsUser.getChartValue();

                // String chartValue = chartDateTto.getChartValue();
                String chartValue = chartConfigsUser.getChartValue();

                List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());

                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode chartValueJson = objectMapper.readTree(chartValue);

                // 获取dataset节点并替换source节点
                ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                for (JsonNode node : dataset) {
                    if (node.has("source")) {
                        ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                        break;
                    }
                }
                // 移除集合中第一个对象的第一个元素
                if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                    lists.get(0).remove(0);
                }

                // 获取series节点并替换name字段
                ArrayNode series = (ArrayNode) chartValueJson.path("series");
                List<String> names = lists.isEmpty() ? Collections.emptyList() : lists.get(0);
                for (int i = 0; i < series.size() && i < names.size(); i++) {
                    JsonNode seriesItem = series.get(i);
                    if (seriesItem.has("name")) {
                        ((com.fasterxml.jackson.databind.node.ObjectNode) seriesItem).put("name", names.get(i));
                    }
                }
                // 获取legend节点并更新data
                JsonNode legend = chartValueJson.path("legend");
                ChartDataUtils.updateLegendData(legend, lists);
                String updatedChartValue = chartValueJson.toString();
                ChartSmartVo chartSmartVo = new ChartSmartVo();
                chartSmartVo.setConfigValue(updatedChartValue);
                chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                // newList.add(chartSmartVo);
                System.out.println("---------------------------------------------");
                System.out.println(updatedChartValue);
                System.out.println("---------------------------------------------");
                newLista.add(chartSmartVo);

            }
            return AjaxResult.success(newLista);
            //柱状图
        } else if (chartType == null) {
            ArrayList<ChartSmartVo> newListb = new ArrayList<>();
            for (ChartConfigsUser chartConfigsUser : list) {

                List<List<String>> getdata = extractDataFromList(chartDateTto.getDataList());
                String chartValue = chartConfigsUser.getChartValue();

                List<Map> roomName = new ArrayList<>();
                List<String> strings = getdata.get(1);
                HashMap<String, String> map = new HashMap<>();
                map.put("name", strings.get(0));
                roomName.add(map);

                List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());

                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode chartValueJson = objectMapper.readTree(chartValue);

                // 获取dataset节点并替换source节点
                JsonNode datasetNode = chartValueJson.path("dataset");

                if (datasetNode.isArray()) {
                    ArrayNode dataset = (ArrayNode) datasetNode;
                    for (JsonNode node : dataset) {
                        if (node.has("source")) {
                            ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                            break;
                        }
                    }
                } else if (datasetNode.isObject()) {
                    ObjectNode dataset = (ObjectNode) datasetNode;
                    if (dataset.has("source")) {
                        dataset.set("source", objectMapper.valueToTree(lists));
                    }
                }

                // 移除集合中第一个对象的第一个元素
                if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                    lists.get(0).remove(0);
                }

                // 获取series节点并替换name字段
                ArrayNode series = (ArrayNode) chartValueJson.path("series");
                List<String> names = lists.isEmpty() ? Collections.emptyList() : lists.get(0);
                for (int i = 0; i < series.size() && i < names.size(); i++) {
                    JsonNode seriesItem = series.get(i);
                    if (seriesItem.has("name")) {
                        ((com.fasterxml.jackson.databind.node.ObjectNode) seriesItem).put("name", names.get(i));
                    }
                }
                // 获取legend节点并更新data
                JsonNode legend = chartValueJson.path("legend");
                ChartDataUtils.updateLegendData(legend, lists);
                String updatedChartValue = chartValueJson.toString();


                ChartSmartVo chartSmartVo = new ChartSmartVo();
                chartSmartVo.setConfigValue(updatedChartValue);
                chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                newListb.add(chartSmartVo);


            }
            return AjaxResult.success(newListb);

        } else if (chartType == 6) { //饼图
            ArrayList<ChartSmartVo> newListc = new ArrayList<>();
            for (ChartConfigsUser chartConfigsUser : list) {

                //chart_configs_interface的config_id 等于 chart_configs的id字段
                Integer id = chartDateTto.getConfigId();

                String chartValue = chartConfigsUser.getChartValue();
                List<Map<String, Object>> originalMapList = chartDateTto.getDataList();

                // 移除第一个对象
                if (!originalMapList.isEmpty()) {
                    originalMapList.remove(0);
                }

                // 将 List<Map<String, Object>> 转换为 List<List<Object>>
                List<List<Object>> lists = convertDataList(originalMapList);

                // 从第二个list开始，每个list的元素除了第一个，其他转换为整数类型
                for (int i = 1; i < lists.size(); i++) {
                    List<Object> row = lists.get(i);
                    for (int j = 1; j < row.size(); j++) {
                        if (row.get(j) instanceof String) {
                            try {
                                row.set(j, Double.parseDouble((String) row.get(j)));
                            } catch (NumberFormatException e) {
                                // 如果转换失败，保留原字符串
                            }
                        }
                    }
                }
                // 移除第一个对象
                List<List<Object>> modifiedLists = new ArrayList<>(lists);
                if (!modifiedLists.isEmpty()) {
                    modifiedLists.remove(0);
                }

                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode chartValueJson = objectMapper.readTree(chartValue);
                // 获取 dataset 节点
                ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");

                // 找到 source 节点并替换它，保留第一个对象
                for (JsonNode node : dataset) {
                    if (node.has("source")) {
                        ArrayNode originalSource = (ArrayNode) node.get("source");
                        ArrayNode newSource = objectMapper.createArrayNode();

                        // 保留第一个对象
                        if (originalSource.size() > 0) {
                            newSource.add(originalSource.get(0));
                        }

                        // 将修改后的数据逐项添加到 newSource 中
                        ArrayNode modifiedSource = objectMapper.valueToTree(modifiedLists);
                        for (JsonNode jsonNode : modifiedSource) {
                            newSource.add(jsonNode);
                        }

                        ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", newSource);
                        break;
                    }
                }

                String updatedChartValue = chartValueJson.toString();

                ChartSmartVo chartSmartVo = new ChartSmartVo();
                chartSmartVo.setConfigValue(updatedChartValue);
                chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                newListc.add(chartSmartVo);

            }
            return AjaxResult.success(newListc);

        } else if (chartType == 5) {
            ArrayList<ChartSmartVo> newListd = new ArrayList<>();
            for (ChartConfigsUser chartConfigsUser : list) {
                String configValue = chartConfigsUser.getChartValue();
                List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

                int size = lists.get(0).size(); // 假设所有列长度一致
                int group = size / 2;
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode chartValueJson = objectMapper.readTree(configValue);
                // 获取 dataset 节点并清空 source
                ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                dataset.removeAll();
                // 根据 group 的数量重新建立 source
                for (int i = 0; i < group; i++) {
                    ArrayNode newSource = objectMapper.createArrayNode();
                    for (List<String> listq : lists) {
                        if (listq.size() > i * 2) {
                            ArrayNode pair = objectMapper.createArrayNode();
                            pair.add(listq.get(i * 2)); // 第一个数据
                            if (listq.size() > i * 2 + 1) {
                                pair.add(listq.get(i * 2 + 1)); // 第二个数据
                            }
                            newSource.add(pair);
                        }
                    }
                    ObjectNode newDatasetObject = objectMapper.createObjectNode();
                    newDatasetObject.set("source", newSource);
                    dataset.add(newDatasetObject);
                }
                // 获取 series 节点并清空
                ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
                seriesArray.removeAll();

                // 重新构建 series，每两个数据为一组
                for (int i = 0; i < group; i++) {
                    ObjectNode seriesObject = objectMapper.createObjectNode();
                    seriesObject.put("name", lists.get(0).get(i * 2)); // 使用第一个数据作为 name
                    seriesObject.put("type", "scatter"); // 假设图表类型为 scatter，可以根据需要调整
                    seriesObject.put("datasetIndex", i);
                    seriesArray.add(seriesObject);
                }

                // 获取 legend 节点并更新 data
                JsonNode legend = chartValueJson.path("legend");
                ChartDataUtils.updateLegendData(legend, lists);
                String updatedChartValue = chartValueJson.toString();

                ChartSmartVo chartSmartVo = new ChartSmartVo();
                chartSmartVo.setConfigValue(updatedChartValue);
                chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                newListd.add(chartSmartVo);
            }
            return AjaxResult.success(newListd);
        } else if (chartType == 13) {
            ArrayList<ChartSmartVo> newListe = new ArrayList<>();
            for (ChartConfigsUser chartConfigsUser : list) {
                String chartValue = chartConfigsUser.getChartValue();
                List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());
                System.out.println(chartValue);
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode chartValueJson = objectMapper.readTree(chartValue);

                // 获取dataset节点并替换source节点
                ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                for (JsonNode node : dataset) {
                    if (node.has("source")) {
                        ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                        break;
                    }
                }
                // 移除集合中第一个对象的第一个元素
                if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                    lists.get(0).remove(0);
                }
                ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");

                // 计算第一个对象元素数量
                int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();
                System.out.println(firstObjectRemainingElements);
                // 如果series字段的对象数量小于第一个集合的数量，循环复制series中的对象使其数量相等
                if (seriesArray.size() < firstObjectRemainingElements) {
                    JsonNode firstSeriesObject = seriesArray.get(0);
                    for (int i = seriesArray.size(); i < firstObjectRemainingElements; i++) {
                        seriesArray.add(firstSeriesObject.deepCopy());
                    }
                } else {
                    // 删除多余的对象
                    while (seriesArray.size() > firstObjectRemainingElements) {
                        seriesArray.remove(seriesArray.size() - 1);
                    }
                }

                // 更新series中每个对象的name字段
                for (int i = 0; i < firstObjectRemainingElements; i++) {
                    ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
                }

                // 获取legend节点并更新data
                JsonNode legend = chartValueJson.path("legend");
                ChartDataUtils.updateLegendData(legend, lists);

                String updatedChartValue = chartValueJson.toString();

                ChartSmartVo chartSmartVo = new ChartSmartVo();
                chartSmartVo.setConfigValue(updatedChartValue);
                chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                newListe.add(chartSmartVo);
            }
            return AjaxResult.success(newListe);
        }

        return null;
    }


    /**
     * 专家图例的查询 查询之后渲染
     * 给ai 用
     *
     * @return
     */
    @PostMapping("/ai/expert/chart/list")
    public AjaxResult queryExpertChartLists(@RequestBody ChartDateTto chartDateTto) throws Exception {
        List<Integer> chartTypeList = chartDateTto.getChartTypeList();

        ArrayList<ChartSmartVo> chartTypeListNull = new ArrayList<>();
        if (chartTypeList == null || chartTypeList.isEmpty()) {
            List<Integer> chartTypes = Arrays.asList(1, 6, 5, 13);
            for (Integer chartType : chartTypes) {
                Long subjectId = chartDateTto.getSubjectId();
                LambdaQueryWrapper<ChartConfigsUser> lqw = new LambdaQueryWrapper<>();
                lqw.eq(ChartConfigsUser::getUserId, 2);
                lqw.eq(ChartConfigsUser::getStatus, 0);
                lqw.eq(ChartConfigsUser::getChartType, chartType);
                if (subjectId != null) {
                    lqw.eq(ChartConfigsUser::getSubjectId, subjectId);
                }
                List<ChartConfigsUser> list = chartConfigsUserService.list(lqw);
                if (chartType == 1) {
                    for (ChartConfigsUser chartConfigsUser : list) {

                        List<List<String>> data = extractDataFromList(chartDateTto.getDataList());
                        String configValue = chartConfigsUser.getChartValue();

                        // String chartValue = chartDateTto.getChartValue();
                        String chartValue = chartConfigsUser.getChartValue();

                        List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());

                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode chartValueJson = objectMapper.readTree(chartValue);

                        // 获取dataset节点并替换source节点
                        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                        for (JsonNode node : dataset) {
                            if (node.has("source")) {
                                ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                                break;
                            }
                        }
                        // 移除集合中第一个对象的第一个元素
                        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                            lists.get(0).remove(0);
                        }

                        // 获取series节点并替换name字段
                        ArrayNode series = (ArrayNode) chartValueJson.path("series");
                        List<String> names = lists.isEmpty() ? Collections.emptyList() : lists.get(0);
                        for (int i = 0; i < series.size() && i < names.size(); i++) {
                            JsonNode seriesItem = series.get(i);
                            if (seriesItem.has("name")) {
                                ((com.fasterxml.jackson.databind.node.ObjectNode) seriesItem).put("name", names.get(i));
                            }
                        }
                        // 获取legend节点并更新data
                        JsonNode legend = chartValueJson.path("legend");
                        ChartDataUtils.updateLegendData(legend, lists);
                        String updatedChartValue = chartValueJson.toString();
                        ChartSmartVo chartSmartVo = new ChartSmartVo();
                        chartSmartVo.setConfigValue(updatedChartValue);
                        chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                        chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                        chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                        chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                        // newList.add(chartSmartVo);
                        System.out.println("---------------------------------------------");
                        System.out.println(updatedChartValue);
                        System.out.println("---------------------------------------------");
                        chartTypeListNull.add(chartSmartVo);

                    }
                    // return AjaxResult.success(newLista);
                    //柱状图
                } else if (chartType == null) {
                    ArrayList<ChartSmartVo> newListb = new ArrayList<>();
                    for (ChartConfigsUser chartConfigsUser : list) {

                        List<List<String>> getdata = extractDataFromList(chartDateTto.getDataList());
                        String chartValue = chartConfigsUser.getChartValue();

                        List<Map> roomName = new ArrayList<>();
                        List<String> strings = getdata.get(1);
                        HashMap<String, String> map = new HashMap<>();
                        map.put("name", strings.get(0));
                        roomName.add(map);

                        List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());

                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode chartValueJson = objectMapper.readTree(chartValue);

                        // 获取dataset节点并替换source节点
                        JsonNode datasetNode = chartValueJson.path("dataset");

                        if (datasetNode.isArray()) {
                            ArrayNode dataset = (ArrayNode) datasetNode;
                            for (JsonNode node : dataset) {
                                if (node.has("source")) {
                                    ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                                    break;
                                }
                            }
                        } else if (datasetNode.isObject()) {
                            ObjectNode dataset = (ObjectNode) datasetNode;
                            if (dataset.has("source")) {
                                dataset.set("source", objectMapper.valueToTree(lists));
                            }
                        }

                        // 移除集合中第一个对象的第一个元素
                        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                            lists.get(0).remove(0);
                        }

                        // 获取series节点并替换name字段
                        ArrayNode series = (ArrayNode) chartValueJson.path("series");
                        List<String> names = lists.isEmpty() ? Collections.emptyList() : lists.get(0);
                        for (int i = 0; i < series.size() && i < names.size(); i++) {
                            JsonNode seriesItem = series.get(i);
                            if (seriesItem.has("name")) {
                                ((com.fasterxml.jackson.databind.node.ObjectNode) seriesItem).put("name", names.get(i));
                            }
                        }
                        // 获取legend节点并更新data
                        JsonNode legend = chartValueJson.path("legend");
                        ChartDataUtils.updateLegendData(legend, lists);
                        String updatedChartValue = chartValueJson.toString();


                        ChartSmartVo chartSmartVo = new ChartSmartVo();
                        chartSmartVo.setConfigValue(updatedChartValue);
                        chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                        chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                        chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                        chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                        chartTypeListNull.add(chartSmartVo);


                    }
                    //return AjaxResult.success(newListb);
                } else if (chartType == 6) { //饼图
                    ArrayList<ChartSmartVo> newListc = new ArrayList<>();
                    for (ChartConfigsUser chartConfigsUser : list) {

                        //chart_configs_interface的config_id 等于 chart_configs的id字段
                        Integer id = chartDateTto.getConfigId();

                        String chartValue = chartConfigsUser.getChartValue();
                        List<Map<String, Object>> originalMapList = chartDateTto.getDataList();

                        // 移除第一个对象
                        if (!originalMapList.isEmpty()) {
                            originalMapList.remove(0);
                        }


                        // 将 List<Map<String, Object>> 转换为 List<List<Object>>
                        List<List<Object>> lists = convertDataList(originalMapList);

                        // 从第二个list开始，每个list的元素除了第一个，其他转换为整数类型
                        for (int i = 1; i < lists.size(); i++) {
                            List<Object> row = lists.get(i);
                            for (int j = 1; j < row.size(); j++) {
                                if (row.get(j) instanceof String) {
                                    try {
                                        row.set(j, Double.parseDouble((String) row.get(j)));
                                    } catch (NumberFormatException e) {
                                        // 如果转换失败，保留原字符串
                                    }
                                }
                            }
                        }

                        // 移除第一个对象
                        List<List<Object>> modifiedLists = new ArrayList<>(lists);
                        if (!modifiedLists.isEmpty()) {
                            modifiedLists.remove(0);
                        }

                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode chartValueJson = objectMapper.readTree(chartValue);
                        // 获取 dataset 节点
                        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");

                        // 找到 source 节点并替换它，保留第一个对象
                        for (JsonNode node : dataset) {
                            if (node.has("source")) {
                                ArrayNode originalSource = (ArrayNode) node.get("source");
                                ArrayNode newSource = objectMapper.createArrayNode();

                                // 保留第一个对象
                                if (originalSource.size() > 0) {
                                    newSource.add(originalSource.get(0));
                                }

                                // 将修改后的数据逐项添加到 newSource 中
                                ArrayNode modifiedSource = objectMapper.valueToTree(modifiedLists);
                                for (JsonNode jsonNode : modifiedSource) {
                                    newSource.add(jsonNode);
                                }

                                ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", newSource);
                                break;
                            }
                        }

                        String updatedChartValue = chartValueJson.toString();

                        ChartSmartVo chartSmartVo = new ChartSmartVo();
                        chartSmartVo.setConfigValue(updatedChartValue);
                        chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                        chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                        chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                        chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                        chartTypeListNull.add(chartSmartVo);

                    }
                    // return AjaxResult.success(newListc);

                } else if (chartType == 5) {
                    ArrayList<ChartSmartVo> newListd = new ArrayList<>();
                    for (ChartConfigsUser chartConfigsUser : list) {
                        String configValue = chartConfigsUser.getChartValue();
                        List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

                        int size = lists.get(0).size(); // 假设所有列长度一致
                        int group = size / 2;
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode chartValueJson = objectMapper.readTree(configValue);
                        // 获取 dataset 节点并清空 source
                        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                        dataset.removeAll();
                        // 根据 group 的数量重新建立 source
                        for (int i = 0; i < group; i++) {
                            ArrayNode newSource = objectMapper.createArrayNode();
                            for (List<String> listq : lists) {
                                if (listq.size() > i * 2) {
                                    ArrayNode pair = objectMapper.createArrayNode();
                                    pair.add(listq.get(i * 2)); // 第一个数据
                                    if (listq.size() > i * 2 + 1) {
                                        pair.add(listq.get(i * 2 + 1)); // 第二个数据
                                    }
                                    newSource.add(pair);
                                }
                            }
                            ObjectNode newDatasetObject = objectMapper.createObjectNode();
                            newDatasetObject.set("source", newSource);
                            dataset.add(newDatasetObject);
                        }
                        // 获取 series 节点并清空
                        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
                        seriesArray.removeAll();

                        // 重新构建 series，每两个数据为一组
                        for (int i = 0; i < group; i++) {
                            ObjectNode seriesObject = objectMapper.createObjectNode();
                            seriesObject.put("name", lists.get(0).get(i * 2)); // 使用第一个数据作为 name
                            seriesObject.put("type", "scatter"); // 假设图表类型为 scatter，可以根据需要调整
                            seriesObject.put("datasetIndex", i);
                            seriesArray.add(seriesObject);
                        }

                        // 获取 legend 节点并更新 data
                        JsonNode legend = chartValueJson.path("legend");
                        ChartDataUtils.updateLegendData(legend, lists);
                        String updatedChartValue = chartValueJson.toString();

                        ChartSmartVo chartSmartVo = new ChartSmartVo();
                        chartSmartVo.setConfigValue(updatedChartValue);
                        chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                        chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                        chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                        chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                        chartTypeListNull.add(chartSmartVo);
                    }
                    // return AjaxResult.success(newListd);
                } else if (chartType == 13) {
                    ArrayList<ChartSmartVo> newListe = new ArrayList<>();
                    for (ChartConfigsUser chartConfigsUser : list) {
                        String chartValue = chartConfigsUser.getChartValue();
                        List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());
                        System.out.println(chartValue);
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode chartValueJson = objectMapper.readTree(chartValue);

                        // 获取dataset节点并替换source节点
                        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                        for (JsonNode node : dataset) {
                            if (node.has("source")) {
                                ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                                break;
                            }
                        }
                        // 移除集合中第一个对象的第一个元素
                        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                            lists.get(0).remove(0);
                        }
                        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");

                        // 计算第一个对象元素数量
                        int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();
                        System.out.println(firstObjectRemainingElements);
                        // 如果series字段的对象数量小于第一个集合的数量，循环复制series中的对象使其数量相等
                        if (seriesArray.size() < firstObjectRemainingElements) {
                            JsonNode firstSeriesObject = seriesArray.get(0);
                            for (int i = seriesArray.size(); i < firstObjectRemainingElements; i++) {
                                seriesArray.add(firstSeriesObject.deepCopy());
                            }
                        } else {
                            // 删除多余的对象
                            while (seriesArray.size() > firstObjectRemainingElements) {
                                seriesArray.remove(seriesArray.size() - 1);
                            }
                        }

                        // 更新series中每个对象的name字段
                        for (int i = 0; i < firstObjectRemainingElements; i++) {
                            ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
                        }

                        // 获取legend节点并更新data
                        JsonNode legend = chartValueJson.path("legend");
                        ChartDataUtils.updateLegendData(legend, lists);

                        String updatedChartValue = chartValueJson.toString();

                        ChartSmartVo chartSmartVo = new ChartSmartVo();
                        chartSmartVo.setConfigValue(updatedChartValue);
                        chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                        chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                        chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                        chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                        chartTypeListNull.add(chartSmartVo);
                    }
                    // return AjaxResult.success(newListe);
                }


            }

            return AjaxResult.success(chartTypeListNull);
        }

        System.out.println("-------------------------------分割线-------------------");
        ArrayList<ChartSmartVo> newLists = new ArrayList<>();
        for (Integer chartType : chartTypeList) {
            Long subjectId = chartDateTto.getSubjectId();
            LambdaQueryWrapper<ChartConfigsUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ChartConfigsUser::getUserId, 2);
            lqw.eq(ChartConfigsUser::getStatus, 0);
            lqw.eq(ChartConfigsUser::getChartType, chartType);

            if (subjectId != null) {
                lqw.eq(ChartConfigsUser::getSubjectId, subjectId);
            }
            List<ChartConfigsUser> list = chartConfigsUserService.list(lqw);
            if (chartType == 1) {
                ArrayList<ChartSmartVo> newLista = new ArrayList<>();
                for (ChartConfigsUser chartConfigsUser : list) {

                    List<List<String>> data = extractDataFromList(chartDateTto.getDataList());
                    String configValue = chartConfigsUser.getChartValue();

                    // String chartValue = chartDateTto.getChartValue();
                    String chartValue = chartConfigsUser.getChartValue();

                    List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());

                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode chartValueJson = objectMapper.readTree(chartValue);

                    // 获取dataset节点并替换source节点
                    ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                    for (JsonNode node : dataset) {
                        if (node.has("source")) {
                            ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                            break;
                        }
                    }
                    // 移除集合中第一个对象的第一个元素
                    if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                        lists.get(0).remove(0);
                    }

                    // 获取series节点并替换name字段
                    ArrayNode series = (ArrayNode) chartValueJson.path("series");
                    List<String> names = lists.isEmpty() ? Collections.emptyList() : lists.get(0);
                    for (int i = 0; i < series.size() && i < names.size(); i++) {
                        JsonNode seriesItem = series.get(i);
                        if (seriesItem.has("name")) {
                            ((com.fasterxml.jackson.databind.node.ObjectNode) seriesItem).put("name", names.get(i));
                        }
                    }
                    // 获取legend节点并更新data
                    JsonNode legend = chartValueJson.path("legend");
                    ChartDataUtils.updateLegendData(legend, lists);
                    String updatedChartValue = chartValueJson.toString();
                    ChartSmartVo chartSmartVo = new ChartSmartVo();
                    chartSmartVo.setConfigValue(updatedChartValue);
                    chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                    chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                    chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                    chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                    // newList.add(chartSmartVo);
                    System.out.println("---------------------------------------------");
                    System.out.println(updatedChartValue);
                    System.out.println("---------------------------------------------");
                    newLists.add(chartSmartVo);

                }
                // return AjaxResult.success(newLista);
                //柱状图
            } else if (chartType == null) {
                ArrayList<ChartSmartVo> newListb = new ArrayList<>();
                for (ChartConfigsUser chartConfigsUser : list) {

                    List<List<String>> getdata = extractDataFromList(chartDateTto.getDataList());
                    String chartValue = chartConfigsUser.getChartValue();

                    List<Map> roomName = new ArrayList<>();
                    List<String> strings = getdata.get(1);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("name", strings.get(0));
                    roomName.add(map);

                    List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());

                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode chartValueJson = objectMapper.readTree(chartValue);

                    // 获取dataset节点并替换source节点
                    JsonNode datasetNode = chartValueJson.path("dataset");

                    if (datasetNode.isArray()) {
                        ArrayNode dataset = (ArrayNode) datasetNode;
                        for (JsonNode node : dataset) {
                            if (node.has("source")) {
                                ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                                break;
                            }
                        }
                    } else if (datasetNode.isObject()) {
                        ObjectNode dataset = (ObjectNode) datasetNode;
                        if (dataset.has("source")) {
                            dataset.set("source", objectMapper.valueToTree(lists));
                        }
                    }

                    // 移除集合中第一个对象的第一个元素
                    if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                        lists.get(0).remove(0);
                    }

                    // 获取series节点并替换name字段
                    ArrayNode series = (ArrayNode) chartValueJson.path("series");
                    List<String> names = lists.isEmpty() ? Collections.emptyList() : lists.get(0);
                    for (int i = 0; i < series.size() && i < names.size(); i++) {
                        JsonNode seriesItem = series.get(i);
                        if (seriesItem.has("name")) {
                            ((com.fasterxml.jackson.databind.node.ObjectNode) seriesItem).put("name", names.get(i));
                        }
                    }
                    // 获取legend节点并更新data
                    JsonNode legend = chartValueJson.path("legend");
                    ChartDataUtils.updateLegendData(legend, lists);
                    String updatedChartValue = chartValueJson.toString();


                    ChartSmartVo chartSmartVo = new ChartSmartVo();
                    chartSmartVo.setConfigValue(updatedChartValue);
                    chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                    chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                    chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                    chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                    newLists.add(chartSmartVo);


                }
                //return AjaxResult.success(newListb);

            } else if (chartType == 6) { //饼图
                ArrayList<ChartSmartVo> newListc = new ArrayList<>();
                for (ChartConfigsUser chartConfigsUser : list) {

                    //chart_configs_interface的config_id 等于 chart_configs的id字段
                    Integer id = chartDateTto.getConfigId();

                    String chartValue = chartConfigsUser.getChartValue();
                    List<Map<String, Object>> originalMapList = chartDateTto.getDataList();

                    // 移除第一个对象
                    if (!originalMapList.isEmpty()) {
                        originalMapList.remove(0);
                    }


                    // 将 List<Map<String, Object>> 转换为 List<List<Object>>
                    List<List<Object>> lists = convertDataList(originalMapList);

                    // 从第二个list开始，每个list的元素除了第一个，其他转换为整数类型
                    for (int i = 1; i < lists.size(); i++) {
                        List<Object> row = lists.get(i);
                        for (int j = 1; j < row.size(); j++) {
                            if (row.get(j) instanceof String) {
                                try {
                                    row.set(j, Double.parseDouble((String) row.get(j)));
                                } catch (NumberFormatException e) {
                                    // 如果转换失败，保留原字符串
                                }
                            }
                        }
                    }

                    // 移除第一个对象
                    List<List<Object>> modifiedLists = new ArrayList<>(lists);
                    if (!modifiedLists.isEmpty()) {
                        modifiedLists.remove(0);
                    }

                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode chartValueJson = objectMapper.readTree(chartValue);
                    // 获取 dataset 节点
                    ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");

                    // 找到 source 节点并替换它，保留第一个对象
                    for (JsonNode node : dataset) {
                        if (node.has("source")) {
                            ArrayNode originalSource = (ArrayNode) node.get("source");
                            ArrayNode newSource = objectMapper.createArrayNode();

                            // 保留第一个对象
                            if (originalSource.size() > 0) {
                                newSource.add(originalSource.get(0));
                            }

                            // 将修改后的数据逐项添加到 newSource 中
                            ArrayNode modifiedSource = objectMapper.valueToTree(modifiedLists);
                            for (JsonNode jsonNode : modifiedSource) {
                                newSource.add(jsonNode);
                            }

                            ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", newSource);
                            break;
                        }
                    }

                    String updatedChartValue = chartValueJson.toString();

                    ChartSmartVo chartSmartVo = new ChartSmartVo();
                    chartSmartVo.setConfigValue(updatedChartValue);
                    chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                    chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                    chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                    chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                    newLists.add(chartSmartVo);

                }
                // return AjaxResult.success(newListc);

            } else if (chartType == 5) {
                ArrayList<ChartSmartVo> newListd = new ArrayList<>();
                for (ChartConfigsUser chartConfigsUser : list) {
                    String configValue = chartConfigsUser.getChartValue();
                    List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());

                    int size = lists.get(0).size(); // 假设所有列长度一致
                    int group = size / 2;
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode chartValueJson = objectMapper.readTree(configValue);
                    // 获取 dataset 节点并清空 source
                    ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                    dataset.removeAll();
                    // 根据 group 的数量重新建立 source
                    for (int i = 0; i < group; i++) {
                        ArrayNode newSource = objectMapper.createArrayNode();
                        for (List<String> listq : lists) {
                            if (listq.size() > i * 2) {
                                ArrayNode pair = objectMapper.createArrayNode();
                                pair.add(listq.get(i * 2)); // 第一个数据
                                if (listq.size() > i * 2 + 1) {
                                    pair.add(listq.get(i * 2 + 1)); // 第二个数据
                                }
                                newSource.add(pair);
                            }
                        }
                        ObjectNode newDatasetObject = objectMapper.createObjectNode();
                        newDatasetObject.set("source", newSource);
                        dataset.add(newDatasetObject);
                    }
                    // 获取 series 节点并清空
                    ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
                    seriesArray.removeAll();

                    // 重新构建 series，每两个数据为一组
                    for (int i = 0; i < group; i++) {
                        ObjectNode seriesObject = objectMapper.createObjectNode();
                        seriesObject.put("name", lists.get(0).get(i * 2)); // 使用第一个数据作为 name
                        seriesObject.put("type", "scatter"); // 假设图表类型为 scatter，可以根据需要调整
                        seriesObject.put("datasetIndex", i);
                        seriesArray.add(seriesObject);
                    }

                    // 获取 legend 节点并更新 data
                    JsonNode legend = chartValueJson.path("legend");
                    ChartDataUtils.updateLegendData(legend, lists);
                    String updatedChartValue = chartValueJson.toString();

                    ChartSmartVo chartSmartVo = new ChartSmartVo();
                    chartSmartVo.setConfigValue(updatedChartValue);
                    chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                    chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                    chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                    chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                    newLists.add(chartSmartVo);
                }
                // return AjaxResult.success(newListd);
            } else if (chartType == 13) {
                ArrayList<ChartSmartVo> newListe = new ArrayList<>();
                for (ChartConfigsUser chartConfigsUser : list) {
                    String chartValue = chartConfigsUser.getChartValue();
                    List<List<String>> lists = extractDataFromList(chartDateTto.getDataList());
                    System.out.println(chartValue);
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode chartValueJson = objectMapper.readTree(chartValue);

                    // 获取dataset节点并替换source节点
                    ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
                    for (JsonNode node : dataset) {
                        if (node.has("source")) {
                            ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("source", objectMapper.valueToTree(lists));
                            break;
                        }
                    }
                    // 移除集合中第一个对象的第一个元素
                    if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
                        lists.get(0).remove(0);
                    }
                    ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");

                    // 计算第一个对象元素数量
                    int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();
                    System.out.println(firstObjectRemainingElements);
                    // 如果series字段的对象数量小于第一个集合的数量，循环复制series中的对象使其数量相等
                    if (seriesArray.size() < firstObjectRemainingElements) {
                        JsonNode firstSeriesObject = seriesArray.get(0);
                        for (int i = seriesArray.size(); i < firstObjectRemainingElements; i++) {
                            seriesArray.add(firstSeriesObject.deepCopy());
                        }
                    } else {
                        // 删除多余的对象
                        while (seriesArray.size() > firstObjectRemainingElements) {
                            seriesArray.remove(seriesArray.size() - 1);
                        }
                    }

                    // 更新series中每个对象的name字段
                    for (int i = 0; i < firstObjectRemainingElements; i++) {
                        ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
                    }

                    // 获取legend节点并更新data
                    JsonNode legend = chartValueJson.path("legend");
                    ChartDataUtils.updateLegendData(legend, lists);

                    String updatedChartValue = chartValueJson.toString();

                    ChartSmartVo chartSmartVo = new ChartSmartVo();
                    chartSmartVo.setConfigValue(updatedChartValue);
                    chartSmartVo.setConfigId(chartConfigsUser.getConfigId());
                    chartSmartVo.setConfigName(chartConfigsUser.getChartName());
                    chartSmartVo.setChartTypeId(Long.valueOf(chartConfigsUser.getChartType()));
                    chartSmartVo.setSubjectId(chartConfigsUser.getSubjectId());
                    newLists.add(chartSmartVo);
                }
                // return AjaxResult.success(newListe);
            }

        }
        return AjaxResult.success(newLists);

    }


    /**
     * 更新 legend 中 data 数组的 name 字段
     * 获取legend的第一个对象 获取里面的data 保留data的第一个值 删除剩余的值 然后根据seriesName的size进行复制 然后放入data的name的值
     */
    public static void updateLegendDataNames(ObjectNode updatedJson, List<String> seriesName) {
        // 获取 legend 节点
        JsonNode legendArray = updatedJson.get("legend");
        if (legendArray != null && legendArray.isArray()) {
            for (JsonNode legend : legendArray) {
                if (legend != null && legend.isObject()) {
                    // 获取 legend 中的 data 节点
                    JsonNode data = legend.get("data");
                    if (data != null && data.isArray()) {
                        ArrayNode dataArray = (ArrayNode) data;
                        // 清空数组
                        dataArray.removeAll();
                        // 复制 seriesName.size() 次，并更新 name
                        for (String name : seriesName) {
                            ObjectNode newNode = JsonNodeFactory.instance.objectNode();
                            newNode.put("name", name);
                            dataArray.add(newNode);
                        }
                    } else {
                        // 如果 data 不是数组或者为空，则创建一个新的数组并添加 name 字段
                        ArrayNode newArray = JsonNodeFactory.instance.arrayNode();
                        for (String name : seriesName) {
                            ObjectNode newNode = JsonNodeFactory.instance.objectNode();
                            newNode.put("name", name);
                            newArray.add(newNode);
                        }
                        ((ObjectNode) legend).set("data", newArray);
                    }
                }
            }
        }
    }

    /**
     * 更新热度字段
     *
     * @param id 记录 ID
     * @return AjaxResult 包含更新结果消息
     */
    @PutMapping("/updateHotById")
    public AjaxResult updateHotById(@RequestParam(value = "id") Long id) {
        boolean updated = chartConfigsUserService.updateHotById(id);
        return AjaxResult.success(updated);
    }


    //获取文件夹上下级的关联id
    private List<Long> getIds(Long id) {
        Long userId = SecurityUtils.getUserId();
        List<ChartFiles> list = chartFilesService.list(new LambdaQueryWrapper<ChartFiles>().eq(ChartFiles::getUserId, userId));
        Map<Long, ChartFiles> map = list.stream().collect(Collectors.toMap(ChartFiles::getFileId, ChartFiles -> ChartFiles));
        ArrayList<Long> ids = new ArrayList<>();
        map.forEach((key, value) -> {
            Optional.ofNullable(value.getParentId())
                    .map(map::get)
                    .ifPresent(pFile -> {
                        List<ChartFiles> children = pFile.getChildren();
                        if (children == null) {
                            pFile.setChildren(Stream.of(value).collect(Collectors.toList()));
                        } else {
                            children.add(value);
                        }
                    });
        });

        processChartFiles(map, id, ids);
        return ids;
    }

    private void processChartFiles(Map<Long, ChartFiles> map, Long id, List<Long> ids) {
        ChartFiles chartFiles1 = map.get(id);
        if (chartFiles1 == null) {
            return;
        }

        ids.add(chartFiles1.getFileId());

        if (chartFiles1.getChildren() != null) {
            chartFiles1.getChildren().forEach(child -> processChartFiles(map, child.getFileId(), ids));
        }
    }

    private List<List<String>> extractDataFromList(List<Map<String, Object>> dataList) {
        List<List<String>> extractedData = new ArrayList<>();

        for (Map<String, Object> row : dataList) {

            List<String> rowData = new ArrayList<>();
            for (Map.Entry<String, Object> entry : row.entrySet()) {
                rowData.add(entry.getValue().toString());
            }

            extractedData.add(rowData);
        }
        return extractedData;
    }


}
